package utils

import (
	"fmt"
	"github.com/huaweicloud/huaweicloud-sdk-go-obs/obs"
	"io"
	"net/http"
	"os"
)

func UploadToOBS(filePath, bucketName, objectKey, ak, sk, endpoint string) error {

	file, err := os.Open(filePath)
	if err != nil {
		fmt.Println(err)
		return err
	}
	defer file.Close()

	obsClient, err := obs.New(ak, sk, endpoint)
	if err != nil {
		return err
	}
	defer obsClient.Close()

	input := &obs.PutObjectInput{}
	input.Bucket = bucketName
	input.Key = objectKey
	input.Metadata = map[string]string{"meta": "value"}
	input.Body = file
	res, err := obsClient.PutObject(input)
	if err != nil {
		fmt.Printf("StatusCode:%d, RequestId:%s\n", res.StatusCode, res.RequestId)
		fmt.Printf("ETag:%s, StorageClass:%s\n", res.ETag, res.StorageClass)
		return err
	}
	return nil
}

func DownloadFile(url, destPath string) error {
	resp, err := http.Get(url)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	file, err := os.Create(destPath)
	if err != nil {
		return err
	}
	defer file.Close()

	_, err = io.Copy(file, resp.Body)
	return err
}
